package ml.kupin.cart.interceptor;

import ml.kupin.common.constant.KuPinConstant;
import ml.kupin.common.utils.CookieUtils;
import ml.kupin.common.utils.KuPinResult;
import ml.kupin.pojo.TbUser;
import ml.kupin.sso.service.TokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录状态拦截器，判断用户是否登陆，
 * 如果已登录，将用户信息放入request域中，
 * 方便controller取用。
 * <p>
 * Created by 小柯(Allen Kerr) on 17.5.7 18:36.
 */
public class UserLoginStatusInterceptor4Cart implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Value("${token_cookie_name}")
    private String token_cookie_name;

    //前处理，执行handler之前执行此方法。
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中取token
        String token = CookieUtils.getCookieValue(request, token_cookie_name);
        if (StringUtils.isNotBlank(token)) {
            //根据token查redis，找到对应的用户信息
            //调用服务层查询redis中是否有与token对应的数据
            KuPinResult kuPinResult = tokenService.getUserByTokenFromRedis(token);
            if (kuPinResult.getStatus() == KuPinConstant.KuPinResult_status_success) {
                TbUser user = (TbUser) kuPinResult.getData();
                //将用户信息放入request中
                request.setAttribute("user", user);
            }
        }
        //放行
        return true;
    }

    //handler执行之后，返回ModeAndView之前
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    //完成处理，返回ModelAndView之后。如果有异常抛出，可以在此处理。
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
